import { connect } from 'react-redux'
import { Dispatch } from 'redux'
import { toggleTodo } from '@/redux-saga/action' // 切换单个选项完成状态
import { RootState } from '@/redux-saga/reducers'
import { List as AntdList, Button } from 'antd'

interface TodoList {
	id: string
	text: string
	completed: boolean
}

function getVisibleTodos(todos: TodoList[], completed: string) {
	switch (completed) {
		case 'SHOW_COMPLETED':
			return todos.filter((t) => t.completed) // 展示完成
		case 'SHOW_ACTIVE':
			return todos.filter((t) => !t.completed) // 展示未完成
		default:
			return todos // 展示全部
	}
}

// state 即 vuex 的总状态，在 reducer/index.js 中定义
const mapStateToProps = (state: RootState) => {
	return {
		todos: getVisibleTodos(state.todos, state.visibilityFilter)
	}
}
// 封装 action
const mapDispatchToProps = (dispatch: Dispatch) => {
	return {
		onTodoClick: (id: string) => {
			dispatch(toggleTodo(id)) // 切换完成状态
		}
	}
}
interface IListProps {
	todos: TodoList[]
	onTodoClick: (id: string) => void
}
const List: React.FC<IListProps> = ({ todos, onTodoClick }) => {
	return (
		<AntdList
			dataSource={todos}
			renderItem={(todo) => {
				return (
					<AntdList.Item style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
						<AntdList.Item.Meta title={todo.text} />
						<Button type="primary" onClick={() => onTodoClick(todo.id)}>
							{todo.completed ? '取消' : '完成'}
						</Button>
					</AntdList.Item>
				)
			}}
		/>
	)
}
export default connect(mapStateToProps, mapDispatchToProps)(List)
